/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: MarketFragment.java
 *   @Date: 19-1-8 下午8:04
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.market.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.market.adapter.FragmentAdapter;
import io.bhex.app.market.bean.FavoriteRecordBean;
import io.bhex.app.market.presenter.MarketPresenter;
import io.bhex.app.utils.BasicFunctionsUtil;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.sdk.config.bean.BasicFunctionsConfig;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.QuoteTokensBean;


public class MarketFragment extends BaseFragment<MarketPresenter,MarketPresenter.MarketUI> implements MarketPresenter.MarketUI {

    private ViewPager viewPager;
//    private TabLayout tab;
    private SegmentTabLayout tab;
    private ArrayList<Pair<String, Fragment>> items;
    private FragmentAdapter marketAdapter;
    BBMarketFragment bbMarketFragment;
    OptionMarketFragment optionMarketFragment;
    private boolean isVisible;
    private BasicFunctionsConfig basicFunctionsConfig;
    private Pair<String, Fragment> bbMarketFragmentPair;
    private Pair<String, Fragment> optionMarketFragmentPair;
    private PerpetualMarketFragment futuresMarketFragment;
    private Pair<String, Fragment> futuresMarketFragmentPair;
    private View tabline;
    private OptionalMarketFragment optionalFragment;
    private Pair<String, Fragment> optionalFragmentPair;
    private TopBar topBar;

    public interface HomeMarktControl {
        boolean IsSelected();
    }

    @Override
    protected MarketPresenter.MarketUI getUI() {
        return this;
    }

    @Override
    protected MarketPresenter createPresenter() {
        return new MarketPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_market_layout, null, false);
    }

    @Override
    protected void initViews() {
        super.initViews();
        basicFunctionsConfig = BasicFunctionsUtil.getBasicFunctionsConfig();
        //设置topbar标题
        initSetTopBar();
        viewPager = viewFinder.find(R.id.viewPager);
        tab = viewFinder.find(R.id.tab);
        tabline = viewFinder.find(R.id.tabline);

        initFragmentTab();
    }

    /**
     * 初始化设置topBar
     */
    private void initSetTopBar() {
        topBar = viewFinder.find(R.id.topBar);
        topBar.setLeftImg(R.mipmap.icon_edit);
        topBar.setRightImg(R.mipmap.icon_search);
        String logoUrl = MMKVManager.getInstance().loadHomeLogoUrl();
        if (TextUtils.isEmpty(logoUrl)) {
            topBar.setTitle(getResources().getString(R.string.string_market));
        }else{
            topBar.setTitle("");
            ImageView titleIcon = topBar.getTitleIcon();
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) titleIcon.getLayoutParams();
            layoutParams.height = PixelUtils.dp2px(24);
            titleIcon.setLayoutParams(layoutParams);
            titleIcon.setVisibility(View.VISIBLE);
            Glide.with(getActivity())
                    .load(logoUrl)
                    .fitCenter()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .skipMemoryCache(false)
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            topBar.setTitle(getResources().getString(R.string.string_market));
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(titleIcon);
        }

        topBar.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.goEditOptional(getActivity());
            }
        });
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.goSearch(getActivity());
            }
        });
        topBar.setTitleGravity();
    }

    @Override
    protected void addEvent() {
        super.addEvent();
    }

    @Override
    public void onResume() {
        super.onResume();
        tab.setTextSelectColor(getResources().getColor(CommonUtil.isBlackMode() ? R.color.dark_night : R.color.white));
    }

    private void initFragmentTab() {

        ArrayList<String> titles = new ArrayList<String>();
        ArrayList<Fragment> fragments = new ArrayList<Fragment>();
        items = new ArrayList<>();
        //自选
        optionalFragment = new OptionalMarketFragment();
        QuoteTokensBean.TokenItem tokenItem = new QuoteTokensBean.TokenItem();
        tokenItem.setTabName(AppData.KEY_FAVORITE);
        Bundle bundle = new Bundle();
        bundle.putSerializable("tradeType", MarketListFragment.TYPE_BB);
        bundle.putSerializable("tabToken", tokenItem);
        optionalFragment.setArguments(bundle);
        optionalFragmentPair = new Pair<String, Fragment>(getString(R.string.string_favorite),optionalFragment);
        optionalFragment.setHomeControl(new HomeMarktControl() {

            @Override
            public boolean IsSelected() {
                return viewPager.getCurrentItem() == items.indexOf(optionalFragmentPair);   //自选
            }
        });
        items.add(optionalFragmentPair);
        //币币
        if (!basicFunctionsConfig.isExchange()) {
            bbMarketFragment = new BBMarketFragment();
            bbMarketFragmentPair = new Pair<String, Fragment>(getString(R.string.string_bb),bbMarketFragment);
            bbMarketFragment.setHomeControl(new HomeMarktControl() {

                @Override
                public boolean IsSelected() {
                    return viewPager.getCurrentItem() == items.indexOf(bbMarketFragmentPair);
                }
            });
            items.add(bbMarketFragmentPair);
        }
        //合约
        if (!basicFunctionsConfig.isFuture()) {
            futuresMarketFragment = new PerpetualMarketFragment();
            futuresMarketFragmentPair = new Pair<String, Fragment>(getString(R.string.string_perpetual_contract),futuresMarketFragment);
            futuresMarketFragment.setHomeControl(new HomeMarktControl() {

                @Override
                public boolean IsSelected() {
                    return viewPager.getCurrentItem() == items.indexOf(futuresMarketFragmentPair);
                }
            });
            items.add(futuresMarketFragmentPair);
        }
        //期权
        if (!basicFunctionsConfig.isOption()) {
            optionMarketFragment = new OptionMarketFragment();
            optionMarketFragmentPair = new Pair<String, Fragment>(getString(R.string.string_option),optionMarketFragment);
            optionMarketFragment.setHomeControl(new HomeMarktControl() {

                @Override
                public boolean IsSelected() {
                    return viewPager.getCurrentItem() == items.indexOf(optionMarketFragmentPair);
                }
            });

            items.add(optionMarketFragmentPair);
        }
        if (items.size()>1) {
            tab.setVisibility(View.VISIBLE);
//            tabline.setVisibility(View.VISIBLE);
        }else{
            tab.setVisibility(View.GONE);
            tabline.setVisibility(View.GONE);
        }
        marketAdapter = new FragmentAdapter(getChildFragmentManager(),items);
        viewPager.setAdapter(marketAdapter);
//        tab.setupWithViewPager(viewPager);
//        tab.setTabMode(TabLayout.MODE_FIXED);
//        tab.setTabGravity(TabLayout.GRAVITY_FILL);
//        CommonUtil.setUpIndicatorWidthByReflex2(tab,15,15);


        for (Pair<String, Fragment> item : items) {
            titles.add(item.first);
            fragments.add(item.second);
        }
        String[] strArray = new String[titles.size()];
        String[] titlesArray = titles.toArray(strArray);
        tab.setTabData(titlesArray);
        tab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
//                if(bbMarketFragment != null && position == items.indexOf(bbMarketFragmentPair)&&!basicFunctionsConfig.isExchange()) {
//                    bbMarketFragment.getRealTimeData();
//                }
//                else if(optionMarketFragment != null && position == items.indexOf(optionMarketFragmentPair)&&!basicFunctionsConfig.isOption()) {
//                    optionMarketFragment.getRealTimeData();
//                }
//                else if(futuresMarketFragment != null && position == items.indexOf(futuresMarketFragmentPair)&&!basicFunctionsConfig.isFuture()) {
//                    futuresMarketFragment.getRealTimeData();
//                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setShowEditOptionalBtn(position);
                setArgumentsOfPageSelect(position);
                tab.setCurrentTab(position);
                if(optionalFragment != null && position == items.indexOf(optionalFragmentPair)) {
                    optionalFragment.getCoinPairListData();
                }
                if(bbMarketFragment != null && position == items.indexOf(bbMarketFragmentPair)&&!basicFunctionsConfig.isExchange()) {
                    bbMarketFragment.getRealTimeData();
                }
                else if(optionMarketFragment != null && position == items.indexOf(optionMarketFragmentPair)&&!basicFunctionsConfig.isOption()) {
                    optionMarketFragment.getRealTimeData();
                }
                else if(futuresMarketFragment != null && position == items.indexOf(futuresMarketFragmentPair)&&!basicFunctionsConfig.isFuture()) {
                    futuresMarketFragment.getRealTimeData();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        int currentPage = 0;
        if (items.size() > 1) {
            if (checkHasFavoriteSymbols()) {
                currentPage = 0;    //有自选，默认到自选列表（当前自选列表是tab第0页）
            }else{
                currentPage = 1;    //没有自选，默认到非自选列表
            }
            setArgumentsOfPageSelect(currentPage);
            viewPager.setCurrentItem(currentPage);
        }

    }

    private void setShowEditOptionalBtn(int position) {
        if (position == 0) {
            //自选tab 显示编辑入口
            topBar.getleftImgView().setVisibility(View.VISIBLE);
        }else{
            topBar.getleftImgView().setVisibility(View.GONE);
        }
    }

    private void setArgumentsOfPageSelect(int position) {
        //设置选中参数
        if (items != null) {
            for (int i = 0; i < items.size(); i++) {
                Pair<String, Fragment> pair = items.get(i);
                if (pair != null) {
                    Fragment secondFragment = pair.second;
                    if (secondFragment != null) {
                        Bundle bundle = new Bundle();
                        if (position == i) {
                            bundle.putBoolean("isSelect",true);
                        }else{
                            bundle.putBoolean("isSelect",false);
                        }
                        secondFragment.setArguments(bundle);
                    }
                }
            }
        }
    }

    /**
     * 检查是否有自选币对
     * @return
     */
    private boolean checkHasFavoriteSymbols() {
        FavoriteRecordBean favoriteRecordBean = KlineUtils.getFavorite();
        if (favoriteRecordBean == null) {
            return false;
        }
        List<CoinPairBean> dataFavorite = favoriteRecordBean.getData();
        if (dataFavorite == null) {
            return false;
        }
        if (dataFavorite.size()>0) {
            return true;
        }
        return false;
    }


    @Override
    public void onPause() {
        super.onPause();
        //QuoteApi.UnSubTickers();
    }


    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
        if (isVisible ) {
            initSetTopBar();
            setShowEditOptionalBtn(viewPager.getCurrentItem());
//            if(bbMarketFragment != null && viewPager.getCurrentItem() == items.indexOf(bbMarketFragmentPair)&&!basicFunctionsConfig.isExchange()) {
//                bbMarketFragment.getRealTimeData();
//            }
//            else if(optionMarketFragment != null && viewPager.getCurrentItem() == items.indexOf(optionMarketFragmentPair)&&!basicFunctionsConfig.isOption()) {
//                optionMarketFragment.getRealTimeData();
//            }
//            else if(futuresMarketFragment != null && viewPager.getCurrentItem() == items.indexOf(futuresMarketFragmentPair)&&!basicFunctionsConfig.isFuture()) {
//                futuresMarketFragment.getRealTimeData();
//            }

        }else{
            QuoteApi.UnSubTickers();
        }
    }
}
